from django.shortcuts import render
import re
import random
import redis
import uuid
# 对接前端需要引入的包(微信小程序)
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from django_redis import get_redis_connection
from sts.sts import Sts
import json

from utils.tencent.msg import send_message
from api import models
from api.serializer.account import MessageSerializers, LoginSerializer
import os
from django.conf import settings

from api.serializer.validators import phone_validateor

# Create your views here.


class MessageView(APIView):
    """
    发送短信的接口
    """

    def get(self, request, *args, **kwargs):
        # 1.获取手机号
        # phone = request.query_params.get('phone')

        # 2.手机号格式校验

        # if not re.match(r"^(1[3|4|5|6|7|8|9])\d{9}$", phone):
        #     return Response("手机号格式错误")

        ser = MessageSerializers(data=request.query_params)
        if not ser.is_valid():
            return Response({"status": False, "message": "手机号格式错误"})

        phone = ser.validated_data.get('phone')

        # 3.生成随机验证码

        random_code = random.randint(1000, 9999)

        # TODO tencent.send_message(phone,random_code)

        """
        1.注册腾讯云,开通腾讯云短信
        2.创建应用
                应用名	
                微信小程序
                SDK AppID	
                1400878277

        3.申请签名 个人：使用公众号
            567419	青蛙先生郑健的公众号

        4.申请模板
        2028737	普通短信	模板One

        5.申请腾讯云

            SecretId:AKIDoUzNYUChz3tWx97qnZ6PTKxNbcOwFLDq
            SecretKey:SnxvfDaljV5TghYCdrukRwEJBqJTXnsl

        6.调用相关接口发送短信
            SDK，写好的工具


        """

        # 验证码发送到手机，购买服务器进行发送短信：阿里云/腾讯云,这里使用腾讯云
        ##调用函数发送短信
        # result = send_message(phone,str(random_code))
        # if not result:
        #     return Response({"status":False,"message":"短信发送失败"})

        print(random_code)

        # 5.验证码+手机号保留(30s过期)
        # 5.1 搭建redis服务（云redis）

        conn = get_redis_connection()
        conn.set(phone,random_code,ex=30)

        return Response({"status": True, "message": "发送成功"})




class RegisterModelSerializer(serializers.ModelSerializer):
    telephone = serializers.CharField(label="手机号",max_length=11,validators=[phone_validateor,])
    code = serializers.CharField(label="短信验证码",max_length=4)

    class Meta:
        model = models.UserInfo
        exclude = ['token']

    #钩子函数
    def validate_code(self,value):
        if len(value)!=4:
            raise ValidationError("验证码格式错误")

        if not value.isdecimal():
            raise ValidationError("验证码格式错误")

        phone = self.initial_data.get("telephone")
        conn = get_redis_connection()
        code = conn.get(phone)

        if not code:
            raise ValidationError("验证码过期")

        if value != code.decode("utf-8"):
            raise ValidationError("验证码错误")

        return value





class LoginView(APIView):

    def get(self, request, *args, **kwargs):
        print(request.query_params)

        """
        1.校验手机号是否合法
        2.校验验证码
            -无验证码
            -有验证码，输入错误
            -有验证码，成功


        4.将一些信息返回给小程序
        """
        ser = LoginSerializer(data=request.query_params)

        if not ser.is_valid():
            return Response({"status": False, "message": "验证码错误"})

        # 3.去数据库中获取用户信息(获取/创建)
        phone = ser.validated_data.get("phone")

        user_object = models.UserInfo.objects.filter(telephone=phone).first()
        if not user_object:
            return Response({"status":False,"message":"用户未注册!"})

        # user_object, flag = models.UserInfo.objects.get_or_create(telephone=phone,defaults={"nickname":nickname,"avatar":avatar})


        user_object.token = str(uuid.uuid4())
        user_object.save()

        # user = models.UserInfo.objects.filter(phone=phone).first()
        # if not user:
        #     #创建用户
        #     models.UserInfo.objects.create(phone = phone,token=str(uuid.uuid4()))
        # else:
        #     user.token = str(uuid.uuid4())
        #     user.save()


        return Response({"status": True, "data": {
            "token": user_object.token,
            "phone": phone,"nickname":user_object.nickname,
            "avatar":user_object.avatar,
            "submit_count":user_object.submit_count,
            "fans_count":user_object.fans_count
        }})


    def post(self,request,*args,**kwargs):
        ser = RegisterModelSerializer(data=request.data)
        if not ser.is_valid():
            return Response({"status":False,"message":"验证码错误"})
        telephone = ser.validated_data.get('telephone')
        user_object = models.UserInfo.objects.filter(telephone=telephone).first()
        if user_object:
            return Response({"status":False,"message":"用户已存在!"})
        ser.validated_data.pop('code')

        user_object = models.UserInfo.objects.create(**ser.validated_data)
        user_object.token = str(uuid.uuid4())
        user_object.save()


        return Response({"status":True,"data":{
            "nickname":user_object.nickname,
            "avatar":user_object.avatar,
            "phone":user_object.telephone,
            "token":user_object.token,
            "submit_count":user_object.submit_count,
            "fans_count":user_object.fans_count
        }})



class CredentialView(APIView):

    def get(self, request, *args, **kwargs):
        config = {
            # 请求URL，域名部分必须和domain保持一致
            # 使用外网域名时：https://sts.tencentcloudapi.com/
            # 使用内网域名时：https://sts.internal.tencentcloudapi.com/
            'url': 'https://sts.tencentcloudapi.com/',
            # 域名，非必须，默认为 sts.tencentcloudapi.com
            # 内网域名：sts.internal.tencentcloudapi.com
            'domain': 'sts.tencentcloudapi.com',
            # 临时密钥有效时长，单位是秒
            'duration_seconds': 1800,
            'secret_id': settings.TENCENT_SECRET_ID,
            # 固定密钥
            'secret_key': settings.TENCENT_SECRET_KEY,
            # 设置网络代理
            # 'proxy': {
            #     'http': 'xx',
            #     'https': 'xx'
            # },
            # 换成你的 bucket
            'bucket': 'zj-1323324849',
            # 换成 bucket 所在地区
            'region': 'ap-nanjing',
            # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
            # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            'allow_prefix': ['*'],
            # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allow_actions': [
                # 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject',
                'name/cos:DeleteObject',
                # # 分片上传
                # 'name/cos:InitiateMultipartUpload',
                # 'name/cos:ListMultipartUploads',
                # 'name/cos:ListParts',
                # 'name/cos:UploadPart',
                # 'name/cos:CompleteMultipartUpload'
            ],
            # 临时密钥生效条件，关于condition的详细设置规则和COS支持的condition类型可以参考 https://cloud.tencent.com/document/product/436/71306
            #     "condition": {
            #         "ip_equal": {
            #             "qcs:ip": [
            #                 "10.217.182.3/24",
            #                 "111.21.33.72/24",
            #             ]
            #         }
            #     }
        }

        try:
            sts = Sts(config)
            response = sts.get_credential()
            # print('get data : ' + json.dumps(dict(response), indent=4))
            return Response(response)
        except Exception as e:
            print(e)



